<?php
	include("../includes/main_inc.php");
	include("../../functions.inc.php");
	//print_r($_POST['IFields']);
	$SearchFields="";
	$ResRow=array();
	if(is_array($_POST['IFields'])){
		$First=true;
		foreach($_POST['IFields'] as $Field){
			$tmp=($First ? "" : ",");
			$First=false;
			$SearchFields.=$tmp.$Field;
		}
		if($_POST['OptVal']!="all"){
			$SOpt=" AND emailSubscribe=".($_POST['OptVal']=="yes" ? 1 : 0);
		}else{
			$SOpt="";	
		}
		$SQL="SELECT $SearchFields FROM members WHERE joined>='".SwapDates($_POST['SFrom'])."' AND joined<='".SwapDates($_POST['STo'])."' $SOpt ORDER BY $_POST[SOrder]";
		//print $SQL;
		$rslt=$r->RawQuery($SQL);
		while($myrow=mysql_fetch_assoc($rslt)){
			$ResRow[]=$myrow;	
		}
	}
	if($_POST['EType']=="csv"){

		header('Content-Type: application/octet-stream');
		header('Content-Disposition: attachment; filename="memberlist-'.date("Y-m-d").'.csv"');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
	
	
	$FirstRow=true;
	$FirstRowText="";
	foreach ($ResRow as $myrow) {
		$FirstColumn=true;
		$RowText="";
		foreach($myrow as $key=>$val){
			$seperator=($FirstColumn ? "" : ",");
			if($FirstRow){
				$FirstRowText.=$seperator.$key;
			}
			$RowText.=$seperator.(eregi(",",$val) ? '"'.$val.'"' : $val);
			$FirstColumn=false;
		}
		if($FirstRow){
			$RowText=$FirstRowText."\n".$RowText."\n";
		}else{
			$RowText.="\n";
		}
		
		print $RowText;
		
		$FirstRow=false;
	};
 }elseif($_POST['EType']=="html"){ ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
	<title>untitled</title>
	<meta http-equiv="content-type" content="text/html;charset=utf-8" />
	<meta name="generator" content="Geany 0.10.2" />
</head>

<body>
	<table border="1">
	<?
		$FirstRowText="<tr>";
		$FirstRow=true;
		foreach ($ResRow as $myrow) {
			$RowText="<tr>";
			foreach($myrow as $key=>$val){
				if($FirstRow){
					$FirstRowText.="<td>".$key."</td>";
				}
				$RowText.="<td>".$val."</td>";
			}
			if($FirstRow){
				$RowText=$FirstRowText."</tr>".$RowText."</tr>";
			}else{
				$RowText.="</tr>";
			}
			
			print $RowText;
			$FirstRow=false;
		};
	?>
	</table>
</body>
</html>
<? }else{ 
	header('Content-Type: text/xml-stream');
	header('Content-Disposition: attachment; filename="memberlist-'.date("Y-m-d").'.xml"');
	header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
	echo'<?xml version="1.0" encoding="UTF-8"?>';
?>
<Member_List>
	<?
		$FirstRowText="<tr>";
		foreach ($ResRow as $myrow) {
			$RowText="<Member>";
			foreach($myrow as $key=>$val){
				$RowText.="<$key>".$val."</$key>";
			}
			$RowText.="</Member>";
			
			print $RowText;
		};
	?>
</Member_List>
<? };?>
